//app.js
const Api = require('./api/api.js') 


App({
    onLaunch: function (options) {
        let self = this;
        /**
         * 登录步骤
         * 检查checkSession成功 先检查缓存中的token，再检查userInfo 错误就重新登录定向到auth页面
         * 检查checkSession失败 重新登录 最后重定向到auth页面
        */
        wx.checkSession({
            success: res => {
                // console.log(res, '小程序登录态')
                //检查globalData里面有没有token
                self.globalData.token = wx.getStorageSync('token');
                if (self.globalData.token == undefined || self.globalData.token == null || self.globalData.token == '') {
                    Api.getStorage('token').then(res => {
                        self.globalData.token = res.data
                        return Api.getStorage('userInfo')
                    })
                    .then(res => {
                        self.globalData.userInfo = res.data
                    })
                    .catch(err => {
                        if (err.errMsg.length != 0) {
                            wx.login({
                                success: res => {
                                    wx.setStorageSync('code', res.code)
									//重新授权
									wx.redirectTo({
										url: '/pages/auth/auth?loginType=index',
									})
                                }
                            })
                        }
                    })
                }
                // 获取个人信息判断
                self.globalData.userInfo = wx.getStorageSync('userInfo');
                if (self.globalData.userInfo == undefined || self.globalData.userInfo == null || self.globalData.userInfo == ''  ){
					wx.login({
						success: res => {
							wx.setStorageSync('code', res.code)
							//重新授权
							wx.redirectTo({
								url: '/pages/auth/auth?loginType=index',
							})
						}
					})
                }
            },
            fail: err => {
                console.log(err, '小程序登录态失效')
                wx.login({
                    success: res => {
                        console.log('-------login res----------', res)
                        wx.setStorageSync('code', res.code)
                        //重新授权
                        wx.redirectTo({
                            url: '/pages/auth/auth?loginType=index',
                        })
                    }
                })
            }
        })
    },
    globalData: {
        wpid:'',
        token: null,
        userInfo: null,
        code: null,
        loginDomain: 'https://wx.ajiuqian.com/wxapp/zhubingrentong/Api/WxAppApi.ashx',
        mallDomain: 'https://wx.ajiuqian.com/wxapp/zhubingrentong/Api/WxAppProgramApi.aspx',
        payUrl: 'https://wx.ajiuqian.com/wxapp/zhubingrentong/PlugIn/WeChatPay/WXAPPPay.aspx',
    }
})